﻿namespace BagSpaceCreator
{
    using Styx;
    using Styx.Common;
    using Styx.Common.Helpers;
    using Styx.CommonBot;
    using Styx.CommonBot.Frames;
    using Styx.CommonBot.Inventory;
    using Styx.CommonBot.Profiles;
    using Styx.Helpers;
    using Styx.Pathing;
    using Styx.Plugins;
    using Styx.WoWInternals;
    using Styx.WoWInternals.Misc;
    using Styx.WoWInternals.World;
    using Styx.WoWInternals.WoWObjects;

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using System.Windows.Media;
    using System.Xml.Linq;

    public class Main : HBPlugin
    {
        public override string Name { get { return "BagSpaceCreator"; } }
        public override string Author { get { return "Pasterke"; } }
        public override Version Version { get { return new Version(1,0); } }

        private string _SavePathDelete = Path.Combine(Utilities.AssemblyDirectory, string.Format(@"Plugins/PluginSettings/Pasterke/DeleteItems-{0}-{1}.txt", StyxWoW.Me.RealmName, StyxWoW.Me.Name));
        private string _SavePathTen = Path.Combine(Utilities.AssemblyDirectory, string.Format(@"Plugins/PluginSettings/Pasterke/UseOnTenList.txt"));
        private string _SavePathFive = Path.Combine(Utilities.AssemblyDirectory, string.Format(@"Plugins/PluginSettings/Pasterke/UseOnFiveList.txt"));
        private string _SavePathThree = Path.Combine(Utilities.AssemblyDirectory, string.Format(@"Plugins/PluginSettings/Pasterke/UseOnThreeList.txt"));
        private string _SavePathOne = Path.Combine(Utilities.AssemblyDirectory, string.Format(@"Plugins/PluginSettings/Pasterke/UseOnOneList.txt"));
        private string _writePath = Path.Combine(Utilities.AssemblyDirectory, string.Format(@"Plugins/PluginSettings/Pasterke/"));

        private List<string> _deleteList = new List<string>();
        private List<string> _useOnTenList = new List<string>();
        private List<string> _useOnFiveList = new List<string>();
        private List<string> _useOnThreeList = new List<string>();
        private List<string> _useOnOneList = new List<string>();

        public bool InventoryCheck = false;
        private bool _init;

        public override bool WantButton { get { return true; } }

        public override void OnButtonPress()
        {
            Form1 ConfigForm = new Form1();
            ConfigForm.ShowDialog();
        }

        public override void Initialize()
        {
            if (_init) return;
            OnEnable();
            Lua.DoString("SetCVar('AutoLootDefault','1')");
            Lua.Events.AttachEvent("LOOT_CLOSED", LootFinished);
            Lua.Events.AttachEvent("MAIL_CLOSED", MailboxFinished);
            Updater.CheckForUpdate(UpdateSettingsBagSpaceCreator.myPrefs.Revision);
            Logging.Write(LogLevel.Normal, Colors.Yellow, "BagSpaceCreator ready for use...");
            CreateDirIfMissing();
            CreateFileIfMissing();
            
            _init = true;
        }

        private void LootFinished(object sender, LuaEventArgs args)
        {
            if (InventoryCheck == false)
            {
                InventoryCheck = true;
            }
        }

        private void MailboxFinished(object sender, LuaEventArgs args)
        {
            if (InventoryCheck == false)
            {
                InventoryCheck = true;
            }
        }
        private void CreateFileIfMissing()
        {
            if (!File.Exists(_SavePathDelete))
            {
                File.Create(_SavePathDelete);
            }
            if (!File.Exists(_SavePathTen))
            {
                File.Create(_SavePathTen);
            }
            if (!File.Exists(_SavePathFive))
            {
                File.Create(_SavePathFive);
            }
            if (!File.Exists(_SavePathThree))
            {
                File.Create(_SavePathThree);
            }
            if (!File.Exists(_SavePathOne))
            {
                File.Create(_SavePathOne);
            }
        }

        private void CreateDirIfMissing()
        {
            bool folderExists = Directory.Exists(_writePath);
            if (!folderExists)
                Directory.CreateDirectory(_writePath);
        }
        private void DeleteItemsToList()
        {
            _deleteList.Clear();
            string f = _SavePathDelete;

            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    _deleteList.Add(line);
                }
            }
            _deleteList.Sort();
        }
        private void UseOnTenToList()
        {
            _useOnTenList.Clear();
            string f = _SavePathTen;

            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    _useOnTenList.Add(line);
                }
            }
            _useOnTenList.Sort();
        }
        private void UseOnFiveToList()
        {
            _useOnFiveList.Clear();
            string f = _SavePathFive;

            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    _useOnFiveList.Add(line);
                }
            }
            _useOnFiveList.Sort();
        }
        private void UseOnThreeToList()
        {
            _useOnThreeList.Clear();
            string f = _SavePathThree;

            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    _useOnThreeList.Add(line);
                }
            }
            _useOnThreeList.Sort();
        }
        private void UseOnOneToList()
        {
            _useOnOneList.Clear();
            string f = _SavePathOne;

            using (StreamReader r = new StreamReader(f))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    _useOnOneList.Add(line);
                }
            }
            _useOnOneList.Sort();
        }

        public override void Pulse()
        {
            if (_init)
                if (StyxWoW.Me.IsActuallyInCombat
                    || StyxWoW.Me.Mounted
                    || StyxWoW.Me.IsDead
                    || StyxWoW.Me.IsGhost
                    )
                {
                    return;
                }

            if (InventoryCheck)
            {
                DeleteItemsToList();
                UseOnTenToList();
                UseOnFiveToList();
                UseOnThreeToList();
                UseOnOneToList();
                foreach (WoWItem item in StyxWoW.Me.BagItems)
                {
                    if (item != null && item.BagSlot != -1 && StyxWoW.Me.FreeNormalBagSlots >= 2)
                    {
                        if (item.Quality == WoWItemQuality.Uncommon
                            && !item.IsSoulbound
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DEGreenBOEItems && item.BagSlot != -1)
                        {
                            //Logging.Write(Colors.Yellow, "Disenchanting: " + item.Name);
                            SpellManager.Cast(13262);
                            Lua.DoString(string.Format("UseContainerItem({0}, {1})", item.BagIndex + 1, item.BagSlot + 1));
                            Thread.Sleep(2500);

                            if (StyxWoW.Me.FreeNormalBagSlots <= 2)
                            {
                                Logging.Write(Colors.Red, "Stopping Because Free Bagspace");
                                break;
                            }
                        }
                        if (item.Quality == WoWItemQuality.Uncommon
                            && item.IsSoulbound
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DEGreenSoulboundItems && item.BagSlot != -1)
                        {
                            //Logging.Write(Colors.Yellow, "Disenchanting: " + item.Name);
                            SpellManager.Cast(13262);
                            Lua.DoString(string.Format("UseContainerItem({0}, {1})", item.BagIndex + 1, item.BagSlot + 1));
                            Thread.Sleep(2500);

                            if (StyxWoW.Me.FreeNormalBagSlots <= 2)
                            {
                                Logging.Write(Colors.Red, "Stopping Because Free Bagspace");
                                break;
                            }
                        }
                        if (item.Quality == WoWItemQuality.Rare
                            && !item.IsSoulbound
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DEBlueBOEItems && item.BagSlot != -1)
                        {

                            SpellManager.Cast(13262);
                            Lua.DoString(string.Format("UseContainerItem({0}, {1})", item.BagIndex + 1, item.BagSlot + 1));
                            Thread.Sleep(2500);

                            if (StyxWoW.Me.FreeNormalBagSlots <= 2)
                            {
                                Logging.Write(Colors.Red, "Stopping Because Free Bagspace");
                                break;
                            }
                        }
                        if (item.Quality == WoWItemQuality.Rare
                            && item.IsSoulbound
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DEBlueSoulboundItems && item.BagSlot != -1)
                        {

                            SpellManager.Cast(13262);
                            Lua.DoString(string.Format("UseContainerItem({0}, {1})", item.BagIndex + 1, item.BagSlot + 1));
                            Thread.Sleep(2500);

                            if (StyxWoW.Me.FreeNormalBagSlots <= 2)
                            {
                                Logging.Write(Colors.Red, "Stopping Because Free Bagspace");
                                break;
                            }
                        }
                        if (item.Quality == WoWItemQuality.Uncommon
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DeleteGreenItems && item.BagSlot != -1)
                        {
                            this.destroyItem(item);
                        }
                        if (item.Quality == WoWItemQuality.Rare
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DeleteBlueItems && item.BagSlot != -1)
                        {
                            this.destroyItem(item);
                        }
                        if (item.Quality == WoWItemQuality.Common
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DeleteWhiteItems && item.BagSlot != -1)
                        {
                            this.destroyItem(item);
                        }
                        if (item.Quality == WoWItemQuality.Poor
                            && (item.ItemInfo.ItemClass == WoWItemClass.Weapon
                            || item.ItemInfo.ItemClass == WoWItemClass.Armor)
                            && SettingsBagSpaceCreator.myPrefs.DeleteGreyItems && item.BagSlot != -1)
                        {
                            this.destroyItem(item);
                        }
                        if (_deleteList.Contains(item.Name))
                        {
                            this.destroyItem(item);
                        }
                        if (_useOnOneList.Contains(item.Name))
                        {
                            if (item.StackCount >= 1)
                            {
                                this.useItem(item);
                            }
                        }
                        else if (_useOnThreeList.Contains(item.Name))
                        {
                            if (item.StackCount >= 3)
                            {
                                this.useItem(item);
                            }
                        }
                        else if (_useOnFiveList.Contains(item.Name))
                        {
                            if (item.StackCount >= 5)
                            {
                                this.useItem(item);
                            }
                        }
                        else if (_useOnTenList.Contains(item.Name))
                        {
                            if (item.StackCount >= 10)
                            {
                                this.useItem(item);
                            }
                        }
                    }
                }
                InventoryCheck = false;
                StyxWoW.SleepForLagDuration();
            }
        }

        private void useItem(WoWItem item)
        {
            Logging.Write(LogLevel.Normal, Colors.Yellow, "[{0} {1}]: Using {2} we have {3}", this.Name, this.Version, item.Name, item.StackCount);
            StyxWoW.SleepForLagDuration();
            Lua.DoString("UseItemByName(\"" + item.Name + "\")");
            StyxWoW.SleepForLagDuration();
        }

        private void destroyItem(WoWItem item)
        {
            Logging.Write(LogLevel.Normal, Colors.Yellow, "[{0} {1}]: Destroying {2} we have {3}", this.Name, this.Version, item.Name, item.StackCount);
            item.PickUp();
            Lua.DoString("DeleteCursorItem()");
            StyxWoW.SleepForLagDuration();
        }
    }
}
